package com.demo.task;

import com.demo.core.ActionContext;
import com.demo.po.ApplicationPo;
import com.demo.po.ServerPo;
import com.demo.service.IApplicationService;
import com.demo.service.IServerService;
import com.jcraft.jsch.Session;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Service;

import java.util.List;

@DisallowConcurrentExecution
@Service
public class ServerCheckTask extends QuartzJobBean {

    protected Logger log = LoggerFactory.getLogger(ServerCheckTask.class);

    @Autowired
    private IServerService serverService;

    @Autowired
    private IApplicationService applicationService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.debug("开始执行服务器检查任务...");
        List<ServerPo> servers = serverService.findAllServers(new ServerPo());
        for (ServerPo server : servers) {
            int oldstatus = server.getStatus();
            Session session = ActionContext.getSession(server);
            int newstatus = (session == null ? 1 : 0);
            if (newstatus != oldstatus)
                serverService.updateServer(server);
        }
        List<ApplicationPo> applications = applicationService.findAllApplications(new ApplicationPo());
        for (ApplicationPo application : applications) {
            int oldstatus = application.getAppstatus();
            ActionContext.testApp(application);
            if (application.getAppstatus() != oldstatus)
                applicationService.updateApplication(application);
        }
        log.debug("服务器状态检查结束");
    }
}
